//
//  GetNewestUtil.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2023/9/4.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit
let newestBillStatus_notification = "newestBillStatus_notification"
class GetNewestUtil_Z:NSObject {
    
    private override init() {}
    static let shared = GetNewestUtil_Z()
    
    private var timer :Timer?
    private var timerCount = 3000 // 还在倒计时，就是true
    var type:TBandJPType = .JP
    // 赋值了ids就开始异步取值
    private var idsArray = [String]()
    
    func appendIds(ids:[String],type:TBandJPType) {
        self.idsArray = ids
        self.type = type
         timerCount = 3000
        self.startTimer()
       
        
    }
    
    
    
    func startTimer() {
         if self.timer.isNone {
            self.timer = Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(self.tickDown), userInfo:nil, repeats:true)
         }
    }
   
   func closeTimer() {
        if timer.isSome {
            timer!.invalidate()
            timer = nil
        }
    }
  
    @objc func tickDown() {
        if timerCount%10 == 0 {
            getNewestInfo()
        }
        timerCount -= 1
  
    }
 
    func getNewestInfo() {
        guard self.idsArray.count > 0 else {
            return
        }
        let topViewController = RouterUtils.currentTopViewController()!

        guard topViewController.isKind(of: ClientHomeVC.self) ||
              topViewController.isKind(of: GYSHomeVC.self) ||
        topViewController.isKind(of: ZyaTenderListVC.self) ||
        topViewController.isKind(of: ZyaTenderInfoVC.self) ||
                topViewController.isKind(of: ZyaTenderBaseForm.self) ||
        topViewController.isKind(of: ZyaTenderJPVC.self) ||
                topViewController.isKind(of: ZyaJPMyMarkVC.self) ||
                topViewController.isKind(of: ZBMyMarkVC.self) ||
        topViewController.isKind(of: ZyaMyTenderJPAllVC.self) ||
        topViewController.isKind(of: ZyaMyTenderJPVC.self) else {
            return
        }
        var api:API!
        if type == .JP {
            api = API.tender(.queryMytenderJpListDetailV3(id_key: self.idsArray.joined(separator: ",")))
        } else {
            api = API.tender(.queryMytenderZbListDetail(id_key: self.idsArray.joined(separator: ",")))
        }
        KSNetwork.shared.doRequest(api,showHud: false) { (data:BaseResult<NewestModel_Z>) in
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                  
                    let userInfo = ["newestBillStatus_data": infos]
                  
                    let notification = Notification(name: Notification.Name(rawValue: newestBillStatus_notification), object: nil, userInfo: userInfo)
                    NotificationCenter.default.post(notification)
                    
                    
                }
            }
         }
    }
     
}
